package com.lei.chinese_herbal_medicine.Controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.lei.chinese_herbal_medicine.Entity.*;
import com.lei.chinese_herbal_medicine.Service.ModelService;
import com.lei.chinese_herbal_medicine.Service.TokenService;
import com.lei.chinese_herbal_medicine.Util.UUIDUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * (Model)表控制层
 *
 * @author makejava
 * @since 2024-01-18 10:05:27
 */
@RestController
public class ModelController {
    /**
     * 服务对象
     */
    @Resource
    private ModelService modelService;
    @Resource
    private TokenService tokenService;
    @Resource
    private Result result;

    Map map=new HashMap<>();
    @PostMapping("/recognition")
    public Result recognition(MultipartFile file, HttpServletRequest request){
        Token token=new Token();
        Map herbAndFlow= new HashMap();
        token.setId(request.getHeader("Authorization"));
        token=tokenService.getToken(token);
        if(token==null){
            herbAndFlow.put("message","未登录，无法识别！");
            result.setCode(403);
            return result;
        }
        String userId=token.getUserId();//待修改为动态的
        if(file==null){
            herbAndFlow.put("message","请查询上传待识别的图片！");
            result.setData(herbAndFlow);
            result.setCode(403);
            return result;
        }
        result=new Result();
        try {
            herbAndFlow = modelService.recognition(userId,file);
            if("图像识别成功！".equals(herbAndFlow.get("message"))){
                result.setCode(200);
            }else{
                result.setCode(403);
            }
        } catch (IOException e) {
            result.setCode(500);
            herbAndFlow.put("message","服务器内部错误，请联系管理员！");
            throw new RuntimeException(e);
        }
        result.setData(herbAndFlow);
        return result;
    }
    @DeleteMapping("/deleteModel")
    public Result deleteModel(@RequestBody Model model){
        boolean is=modelService.deleteModel(model.getId());
        if(is){
            result.setCode(200);
            map.put("message","删除成功");
        }else{
            result.setCode(403);
            map.put("message","删除失败");
        }
        result.setData(map);
        return result;
    }

    @PostMapping("/changeModelStatus")
    public Result changeModelStatus(String targetUseModelId,String currentUseModelId){
        boolean is=modelService.changeModelStatus(targetUseModelId,currentUseModelId);
        map=new HashMap();
        result.setData(map);
        if(is){
            result.setCode(200);
            map.put("message","模型状态改变成功");
        }else{
            result.setCode(403);
            map.put("message","模型状态改变失败");
        }
        return result;
    }
    @GetMapping("/getModelData")
    public Result getModelData(String id){
        result=new Result();
        boolean flag=modelService.getModelData(id,result);
        if (flag){
            result.setCode(200);
            result.getData().put("message","查询成功");
        }else{
            result.setCode(500);
            result.getData().put("message","查询失败");
        }
        return result;
    }
    @GetMapping("/getModelList")
    public Result getModelList(Model model,PageData pageData){
        List<Model> list=modelService.selectByModel(model,pageData);
        result.setCode(200);
        map.put("message","查询成功");
        result.setCount(pageData.getCount());
        result.setList(list);
        result.setData(map);
        return result;
    }

    @PostMapping("/handelModel")
    public Result handelModel(@RequestBody Map<String,Object> modelData){
        Model model=new Model();
        model.setId(UUIDUtil.fastSimpleUUID());
        try{
            model.setModelName((String) modelData.get("modelName"));
            model.setBatchSize(Integer.valueOf((String) modelData.get("batchSize")));
            model.setShuffle((String) modelData.get("shuffle"));
            List<Map<String,String>> list= (List) modelData.get("layerData");
            List<Layer> layers=new ArrayList<>();
            for (Map<String,String> m : list) {
                Layer layer=new Layer();
                layer.setId(UUIDUtil.fastSimpleUUID());
                layer.setLearnRate(Float.valueOf(m.get("learnRate")));
                layer.setFreezeRate(Float.valueOf(m.get("freezeRate")));
                layer.setAttenuationRate(Float.valueOf(m.get("attenuationRate")));
                layer.setEpoch(Integer.valueOf(m.get("epoch")));
                layers.add(layer);
            }
            model.setLayearOne(layers.get(0));
            model.setLayearTwo(layers.get(1));
            model.setLayearThree(layers.get(2));
            //异步启动模型训练
            modelService.handelModel((String) modelData.get("basicModel"),model);
            result.setCode(200);
            map.put("message","启动成功");
        }catch (Exception e){
            result.setCode(403);
            map.put("message","启动失败");
            System.out.println(e.getMessage());
        }
        result.setData(map);
        return result;
    }
}

